import { _decorator, Component, Node, Prefab, instantiate, Vec3, Label, Button, log, UITransform } from 'cc';
import { GridManager } from './GridManager';
import { Block } from './Block';
import { EliminateManager } from './EliminateManager';
const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {
    @property(Prefab)
    blockPrefab: Prefab = null; // 方块预制体

    @property(Node)
    gridNode: Node = null; // 网格节点

    @property(Label)
    scoreLabel: Label = null; // 得分显示

    @property(Button)
    pauseButton: Button = null; // 暂停按钮

    private gridManager: GridManager = null;
    private score: number = 0;
    private isGridReady: boolean = false; // 网格生成标志

    private readonly GRID_COLUMNS = 8; // 网格列数
    private readonly GRID_ROWS = 8; // 网格行数
    private readonly SPACING = 2; // 格子间距

    private eliminateManager: EliminateManager;

    start() {
        this.gridManager = new GridManager(this.GRID_COLUMNS, this.GRID_ROWS);
        this.generateGrid();

        // 初始化得分
        this.updateScore(0);

        // 绑定暂停按钮点击事件
        this.pauseButton.node.on(Button.EventType.CLICK, this.onPause, this);

        this.eliminateManager = new EliminateManager(this.gridManager);
    }

    // 生成网格
    generateGrid() {
        const gridTransform = this.gridNode.getComponent(UITransform);
        const gridWidth = gridTransform.width;
        let gridHeight = gridTransform.height;

        const requiredHeight = this.GRID_ROWS * ((gridHeight / this.GRID_ROWS) - 1) + (this.GRID_ROWS - 1);
        if (gridHeight < requiredHeight) {
            gridHeight = requiredHeight;
            gridTransform.setContentSize(gridWidth, gridHeight);
        }

        const cellWidth = (gridWidth - (this.GRID_COLUMNS - 1) * this.SPACING) / this.GRID_COLUMNS;
        const cellHeight = cellWidth;

        log("cellWidth", cellWidth);
        log("cellHeight", cellHeight);
        const offsetX = -gridWidth / 2 + cellWidth / 2;
        const offsetY = -gridHeight / 2 + cellHeight / 2;
        log("offsetX", offsetX);
        log("offsetY", offsetY);
        for (let x = 0; x < this.GRID_COLUMNS; x++) {
            for (let y = 0; y < this.GRID_ROWS; y++) {
                const block = this.createRandomBlock();
                block.setPosition(new Vec3(x * (cellWidth + this.SPACING) + offsetX, y * (cellHeight + this.SPACING) + offsetY, 0));
                const blockTransform = block.getComponent(UITransform);
                blockTransform.setContentSize(cellWidth, cellHeight);
                this.gridNode.addChild(block);
                this.gridManager.setBlock(x, y, block);
            }
        }
        this.isGridReady = true;
    }

    // 创建随机方块
    createRandomBlock(): Node {
        const block = instantiate(this.blockPrefab);
        const randomValue = Math.random() * 100;
        let type = 0;

        if (randomValue < 80) {
            type = Math.floor(Math.random() * 5); // 5种基本消除元素
        } else if (randomValue < 88) {
            type = 5; // 炸弹道具
        } else if (randomValue < 94) {
            type = 6; // 雪花道具
        } else {
            type = 7; // 冰块道具
        }

        block.getComponent(Block).type = type;
        return block;
    }

    // 更新得分
    updateScore(score: number) {
        this.score = score;
        this.scoreLabel.string = `得分：${this.score}`;
    }

    // 暂停逻辑
    onPause() {
        log('游戏暂停');
        // 这里可以打开暂停菜单或暂停游戏逻辑
    }

    // 检查并执行消除
    checkElimination() {
        if (this.eliminateManager.checkAllEliminations()) {
            // 消除后需要处理的逻辑，比如计分、补充新方块等
            this.handleAfterElimination();
        }
    }

    // 处理消除后的逻辑
    private handleAfterElimination() {
        // TODO: 
        // 1. 更新分数
        // 2. 触发方块下落
        // 3. 生成新方块
    }

    // 掉落逻辑
    dropBlocks() {
        for (let x = 0; x < this.GRID_COLUMNS; x++) {
            for (let y = 0; y < this.GRID_ROWS; y++) {
                if (!this.gridManager.getBlock(x, y)) {
                    for (let yy = y + 1; yy < this.GRID_ROWS; yy++) {
                        const block = this.gridManager.getBlock(x, yy);
                        if (block) {
                            block.setPosition(new Vec3(x * 80, y * 80, 0));
                            this.gridManager.setBlock(x, y, block);
                            this.gridManager.setBlock(x, yy, null);
                            break;
                        }
                    }
                }
            }
        }
    }

    // 生成新方块
    generateNewBlocks() {
        for (let x = 0; x < this.GRID_COLUMNS; x++) {
            for (let y = 0; y < this.GRID_ROWS; y++) {
                if (!this.gridManager.getBlock(x, y)) {
                    const block = this.createRandomBlock();
                    block.setPosition(new Vec3(x * 80, y * 80, 0));
                    this.gridNode.addChild(block);
                    this.gridManager.setBlock(x, y, block);
                }
            }
        }
    }

    update(deltaTime: number) {
        if (!this.isGridReady) return; // 如果网格未生成，直接返回
        this.checkElimination();
        this.dropBlocks();
        this.generateNewBlocks();
    }

    private eliminateBlocks(blocks: Set<Block>) {
        blocks.forEach(block => {
            block.executeEffect(); // 执行特殊效果
            block.eliminate(); // 消除方块
        });
    }
} 